package com.youpai.platform.order.service.service.impl;

import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.exceptions.BaseBizException;
import com.youpai.platform.common.util.StringUtils;
import com.youpai.platform.common.util.UserContext;
import com.youpai.platform.common.util.id.IdGenerator;
import com.youpai.platform.order.service.convert.OrderConverter;
import com.youpai.platform.order.service.entity.po.OrderEvaluatePO;
import com.youpai.platform.order.service.entity.po.OrderPO;
import com.youpai.platform.order.service.enums.OrderStatusEnum;
import com.youpai.platform.order.service.mapper.OrderEvaluateMapper;
import com.youpai.platform.order.service.mapper.OrderMapper;
import com.youpai.platform.order.service.service.OrderEvaluateService;
import com.youpai.platform.order.web.entity.dto.EvaluateDto;
import com.youpai.platform.order.web.entity.req.*;
import com.youpai.platform.order.web.entity.resp.EvaluateResp;
import com.youpai.platform.user.service.entity.po.UserPO;
import com.youpai.platform.user.service.mapper.UserMapper;
import com.youpai.platform.user.web.entity.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @time: 2022/11/27
 * @author: huanghao
 * @description: 评价service实现类
 */
@Slf4j
@Component
public class OrderEvaluateServiceImpl implements OrderEvaluateService {

    @Resource
    private OrderEvaluateMapper orderEvaluateMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public EvaluateResp createEvaluate(CreateEvaluateReq req) {
        //通过登录态 获取用户UID
        UserDTO userDTO = UserContext.getUserContext();
        //做判断，抛用户登录异常
        if (userDTO == null) {
            log.error("用户登录异常!");
            throw new BaseBizException(ProcessCodeEnum.USER_LOGIN_ERROR);
        }
        String uid = userDTO.getUid();
        OrderPO orderPO = orderMapper.get(Long.valueOf(req.getOrderId()));
        //判断技能是否存在
        if (orderPO == null) {
            log.error("当前订单不存在!");
            throw new BaseBizException(ProcessCodeEnum.ORDER_NOT_EXIST);
        }
        //判断当前用户订单下有没有评价
        OrderEvaluatePO isOrderEvaluatePO = orderEvaluateMapper.get(null, Long.valueOf(req.getOrderId()));
        if(isOrderEvaluatePO != null){
            log.error("当前订单已评价，不能重复评价!");
            throw new BaseBizException(ProcessCodeEnum.ORDER_EVALUATE_EXIST);
        }
        //判断登录的用户uid和订单的bossUid是否一样
        if (!userDTO.getUid().equals(String.valueOf(orderPO.getBossUid()))) {
            log.error("当前登录用户和当前订单用户不一致!");
            throw new BaseBizException(ProcessCodeEnum.LOGIN_USER_ORDER_USER_NOT_AGREEMENT);
        }
        OrderEvaluatePO orderEvaluatePO = new OrderEvaluatePO();
        orderEvaluatePO.setEvaluateId(IdGenerator.generateId())
                       .setOrderId(Long.valueOf(req.getOrderId()))
                       .setUserUid(Long.valueOf(uid))
                       .setBossUid(orderPO.getBigGodUid())
                       .setEvaluate(req.getEvaluate())
                       .setStar(req.getStar().doubleValue());
        boolean flag = orderEvaluateMapper.add(orderEvaluatePO) > 0;
        if(flag){
            boolean orderFlag = orderMapper.updateStatus(Long.valueOf(req.getOrderId()), OrderStatusEnum.COMMENTED.status) > 0;
            if(orderFlag == true){
                return new EvaluateResp().setHintText("评价成功!");
            }else {
                log.error("评价失败!");
                throw new BaseBizException(ProcessCodeEnum.EVALUATE_ADD_EXCEPTION);
            }
        }else {
            log.error("评价失败!");
            throw new BaseBizException(ProcessCodeEnum.EVALUATE_ADD_EXCEPTION);
        }
    }

    @Override
    public EvaluateResp removeEvaluate(RemoveEvaluateReq req) {
        OrderEvaluatePO orderEvaluatePO = checkEvaluate(req.getEvaluateId(),req.getOrderId());
        List<Long> ids = Collections.singletonList(orderEvaluatePO.getEvaluateId());
        boolean flag = orderEvaluateMapper.remove(ids) > 0;
        if(flag){
            return new EvaluateResp().setHintText("删除评价信息成功!");
        }else {
            log.error("删除评价信息失败!");
            throw new BaseBizException(ProcessCodeEnum.EVALUATE_REMOVE_EXCEPTION);
        }
    }

    private OrderEvaluatePO checkEvaluate(String evaluateId, String orderId){
        if(StringUtils.isEmpty(evaluateId)){
            log.error("评价ID不能为空：evaluateId - {}", evaluateId);
            throw new BaseBizException(ProcessCodeEnum.EVALUATE_ID_EMPTY);
        }
        if(StringUtils.isEmpty(orderId)){
            log.error("订单ID不能为空：orderId - {}", orderId);
            throw new BaseBizException(ProcessCodeEnum.ORDER_EMPTY);
        }
        OrderEvaluatePO orderEvaluatePO = orderEvaluateMapper.get(Long.valueOf(evaluateId),Long.valueOf(orderId));
        if(orderEvaluatePO == null){
            log.error("当前评价不存在!");
            throw new BaseBizException(ProcessCodeEnum.EVALUATE_NOT_EXIST);
        }
        return orderEvaluatePO;
    }

    @Override
    public List<EvaluateDto> listEvaluate(ListEvaluateReq req) {
        //默认获取前100条
        List<OrderEvaluatePO> orderEvaluatePOS = orderEvaluateMapper.getByOrderId(Long.valueOf(req.getOrderId()), 0, 100);
        List<Long> uids = orderEvaluatePOS.stream().map(OrderEvaluatePO::getUserUid).collect(Collectors.toList());
        List<UserPO> userPOS = userMapper.getUsersByUids(uids);
        Map<Long, String> userNameMap = userPOS.stream().collect(
                Collectors.toMap(UserPO::getUid, UserPO::getNickName));
        if(orderEvaluatePOS.size() > 0){
            return OrderConverter.convertOrderEvaluatePOToEvaluateDTO(orderEvaluatePOS,userNameMap);
        }else {
            return Collections.emptyList();
        }
    }
}
